package com.qfhd.soft.cjzcore.UI;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jaeger.library.StatusBarUtil;
import com.qfhd.soft.cjzcore.CJZManager;
import com.qfhd.soft.cjzcore.Core.CJPermission;
import com.qfhd.soft.cjzcore.Moudle.CJGGKHelper;
import com.qfhd.soft.cjzcore.Moudle.CJImgTaskHelper;
import com.qfhd.soft.cjzcore.Moudle.CJTryPlaceHelper;
import com.qfhd.soft.cjzcore.R;
import com.qfhd.soft.cjzcore.UI.Base.BaseActivity;
import com.qfhd.soft.cjzcore.Core.CJCore;
import com.qfhd.soft.cjzcore.UI.Core.CJActivityManager;
import com.qfhd.soft.cjzcore.UI.Core.DecimalFormatHelper;
import com.qfhd.soft.cjzcore.UI.Custom.CJCardView;
import com.qfhd.soft.cjzcore.UI.Custom.CJDialyDownload;
import com.qfhd.soft.cjzcore.UI.Custom.CJImgTask;
import com.qfhd.soft.cjzcore.UI.Custom.CJLoadingView;
import com.qfhd.soft.cjzcore.UI.Custom.CJSignView;
import com.qfhd.soft.cjzcore.UI.Custom.CJTryPlaceView;
import com.qfhd.soft.cjzcore.UI.Custom.ScratchView;
import com.qfhd.soft.cjzcore.UI.Listener.CJOnlistListener;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.bean.Task_try_Bean;
import com.qfhd.soft.cjzcore.User.CJZUser;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;

public class MainActivity extends BaseActivity {

    private ImageView img_question;

    private QMUIRadiusImageView userIcon;
    private TextView tx_userStatus;
    private RelativeLayout rel_userInfo;

    private TextView tx_coin;
    private LinearLayout lin_coin;

    private TextView tx_money;
    private LinearLayout lin_money;

    private CJSignView signView;
    private CJCardView cardView;
    private CJTryPlaceView tryPlaceView;
    private CJImgTask imgTaskView;
    private CJDialyDownload dialyDownloadView;

    private CJLoadingView loadingView;

    private Activity mActivity;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cjzcoreui_main);
        Log.v("CJZCore", "in cjzcore mainactivity");

        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorTheme), 0);

        mActivity = this;
        mContext = getApplicationContext();

        init();
        initData();
    }

    private void init() {
        img_question = (ImageView) findViewById(R.id.main_question);
        userIcon = (QMUIRadiusImageView) findViewById(R.id.main_user_icon);
        tx_userStatus = (TextView) findViewById(R.id.main_user_status);
        rel_userInfo = (RelativeLayout) findViewById(R.id.main_user_rel);

        tx_coin = (TextView) findViewById(R.id.main_coin);
        lin_coin = (LinearLayout) findViewById(R.id.main_coin_lin);

        tx_money = (TextView) findViewById(R.id.main_money);
        lin_money = (LinearLayout) findViewById(R.id.main_money_lin);

        signView = (CJSignView) findViewById(R.id.main_signView);
        cardView = (CJCardView) findViewById(R.id.main_cardView);
        tryPlaceView = (CJTryPlaceView) findViewById(R.id.main_tryPlaceView);
        imgTaskView = (CJImgTask) findViewById(R.id.main_imgTaskView);
        dialyDownloadView = (CJDialyDownload) findViewById(R.id.main_dialyDownloadView);

        loadingView = (CJLoadingView) findViewById(R.id.main_loadingView);

        showLoadingView();
    }

    private void initData() {
        Log.v("CJZCore", "begain");
        CJPermission.checkAndRequestPermission(getApplicationContext(), mActivity, () -> {
            loadData();
        });
    }

    private void loadData() {
        new Thread(() -> {
            setLoadingViewLoadTip();
            boolean ret = CJZManager.getInstance().getMainAcivityData();
            if (ret) {
                hideLoadingView();
                mActivity.runOnUiThread(() -> {
                    freshUI();
                });
            } else {
                showLoadingView_failed();
            }
        }).start();

    }

    private void showLoadingView() {
        mActivity.runOnUiThread(() -> {
            loadingView.setVisibility(View.VISIBLE);
        });
    }

    private void showLoadingView_failed() {
        mActivity.runOnUiThread(() -> {
            loadingView.setVisibility(View.VISIBLE);
            loadingView.setclickListener(this::loadData);
            loadingView.setfailTip();
        });
    }

    private void setLoadingViewLoadTip() {
        mActivity.runOnUiThread(() -> {
            loadingView.setloadTip();
        });
    }

    private void hideLoadingView() {
        mActivity.runOnUiThread(() -> {
            loadingView.setVisibility(View.GONE);
        });
    }

    private void freshUI() {
        if(CJZUser.getInstance().getUserInfo() == null) return;

        Glide.with(mContext)
                .load(CJZUser.getInstance().getUserInfo().head_image)
                .placeholder(getDrawable(R.drawable.user))
                .centerCrop()
                .into(userIcon);

        String status = CJZUser.getInstance().getUserInfo().isBlindWechat ? "已绑定" : "未绑定";
        tx_userStatus.setText(status);
        tx_coin.setText("" + CJZUser.getInstance().getUserInfo().score);
        tx_money.setText(DecimalFormatHelper.getFloat2(CJCore.getRealMoney_float(CJZUser.getInstance().getUserInfo().balance)));

        //签到
        signView.setSignLength(CJZUser.getInstance().getUserInfo().sign_length);
        signView.setSignBtnListener(() -> {
            signView.beginSign();
            new Thread(()->{
                boolean ret = CJZManager.getInstance().sign();
                if(ret){
                    mActivity.runOnUiThread(()->{
                        signView.signSuccess(CJZUser.getInstance().getUserInfo().sign_length);
                    });
                }
                else{
                    mActivity.runOnUiThread(()->{
                        signView.signFailed();
                    });
                }
            }).start();
        });
        signView.hadSigned(CJZUser.getInstance().getUserInfo().isSign());

        //刮刮卡
        cardView.showHadTip(CJGGKHelper.getInstance().getUnUsedCardSize(),CJGGKHelper.getInstance().getSize());
        cardView.showNextTimeTip(CJGGKHelper.getInstance().getNextTime(),CJGGKHelper.getInstance().getSize());
        cardView.getGgkClickView().setOnClickListener(v -> {
            CJGGKHelper.getInstance().putWatchCard(CJGGKHelper.getInstance().getOneNotUsedSN());
            CJActivityManager.openActivity(mActivity, ScratchActivity.class);
        });

        //试玩任务
        if(tryPlaceView.setData(CJTryPlaceHelper.getInstance().getTryTask_list(),mContext,mActivity)){
            tryPlaceView.setVisibility(View.VISIBLE);
            tryPlaceView.setItemClickListener((view, position) -> {
                Task_try_Bean bean = (Task_try_Bean) tryPlaceView.getDataSource().get(position);
                if (bean.getData().isGetTask) {
                    mActivity.runOnUiThread(() -> {
//                        CJCore.Toast(mContext, "跳转到详情页", false);
                        CJActivityManager.openActivity_String(mActivity, TryTaskDetailActivity.class, bean.getData().tid);
                    });
                } else {
                    mActivity.runOnUiThread(() -> {
                        CJCore.Toast(mContext, "请先获取 " + bean.getData().title + " 任务", false);
                    });
                }
            });
        }
        else{
            tryPlaceView.setVisibility(View.GONE);
        }

        //注册任务
        if(imgTaskView.setData(CJImgTaskHelper.getInstance().getImgTask_list(),mContext)){
            imgTaskView.setVisibility(View.VISIBLE);
            imgTaskView.setItemClickListener((view, position) -> {
                //点击进入详情页
                CJActivityManager.openActivity_String(mActivity,TaskImageActivity.class,CJImgTaskHelper.getInstance().getTid(position));
            });
        }
        else{
            imgTaskView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1024 && hasAllPermissionsGranted(grantResults)) {
            Log.v("CJZCore", "get permission");
//            fetchSplashAD(this, container, skipView, Constants.APPID, getPosId(), this, 0);
            loadData();
        } else {
            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            finish();
        }
    }

    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        freshUI();
    }
}
